﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JustinAngel.MetroBlog.Services.BlogPostService;
using JustinAngel.MetroBlog.Services.Data;
using JustinAngel.MetroBlog.Services.DBContextContainer;
using JustinAngel.MetroBlog.Services.Repository;
using Microsoft.Practices.Unity;

namespace JustinAngel.MetroBlog.Services.CommentService
{
    public class CommentService : ICommentService
    {
        [Dependency]
        public IBlogPostService BlogPostService { get; set; }

        [Dependency]
        public IRepository<Comment> CommentsRepository { get; set; }

        [Dependency]
        public IDBContextContainer DbContextContainer { get; set; }


        public Comment AddComment(string Permlink, string email, string html, string name, int parentCommentID)
        {
            var article = BlogPostService.Get(Permlink, null);

            Comment NewComment = new Comment()
            {
                BlogPost = article,
                ParentComment = article.Comments.FirstOrDefault(c => c.ID == parentCommentID),
                CreatedDate = DateTime.Now,
                Email = email,
                HTML = html,
                Name = name
            };

            if (NewComment.IsValid())
            {
                article.Comments.Add(NewComment);
                CommentsRepository.Insert(NewComment);
                DbContextContainer.CommitChanges();
            }
            else
            {
                NewComment.Delete();
            }

            return NewComment;
        }
    }
}
